package dingtalk

import (
	"errors"
	"fmt"

	"gitee.com/lorock/go-dingtalk-sdk/dingtalkhttplib"

	jsoniter "github.com/json-iterator/go"
	log "github.com/sirupsen/logrus"
)

// AddWorkrecord 发起代办
func (c *Client) AddWorkrecord(info AddTodo) (*AddTodoRsp, error) {
	rsp := new(AddTodoRsp)
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	// 获取 accessToken
	accessToken, err := c.GetAccessToken()
	if err != nil {
		return rsp, err
	}
	param := map[string]string{
		"access_token": accessToken,
	}
	url := fmt.Sprintf("%s?%s", WorkrecordAdd, dingtalkhttplib.URLEncode(param))
	log.Println(url)
	req := dingtalkhttplib.Post(url)
	// 添加请求body数据
	jsonData, err := json.Marshal(info)
	if err != nil {
		return rsp, err
	}
	// str2 := string(jsonData[:])
	// fmt.Println(str2)
	req.Body(jsonData)

	b, err := req.AsBytes()
	if err != nil {
		return rsp, err
	}
	err = json.Unmarshal(b, rsp)
	if err != nil {
		return rsp, err
	}
	if rsp.Errcode != 0 {
		return rsp, errors.New(rsp.Errmsg)
	}
	return rsp, nil
}

// EditWorkrecord 更新代办
func (c *Client) EditWorkrecord(info EditTodo) (*EditTodoRsp, error) {
	rsp := new(EditTodoRsp)
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	// accessToken获取 accessToken
	accessToken, err := c.GetAccessToken()
	if err != nil {
		return rsp, err
	}
	param := map[string]string{
		"access_token": accessToken,
	}
	url := fmt.Sprintf("%s?%s", WorkrecordUpdate, dingtalkhttplib.URLEncode(param))
	log.Println(url)
	req := dingtalkhttplib.Post(url)
	// 添加请求body数据
	jsonData, err := json.Marshal(info)
	if err != nil {
		return rsp, err
	}
	// str2 := string(jsonData[:])
	// fmt.Println(str2)
	req.Body(jsonData)

	b, err := req.AsBytes()
	if err != nil {
		return rsp, err
	}
	err = json.Unmarshal(b, rsp)
	if err != nil {
		return rsp, err
	}
	if rsp.Errcode != 0 {
		return rsp, errors.New(rsp.Errmsg)
	}
	return rsp, nil
}

// GetWorkrecordByUserID 获取用户的待办事项
func (c *Client) GetWorkrecordByUserID(info UserTodoList) (*UserTodoListRsp, error) {
	rsp := new(UserTodoListRsp)
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	// accessToken获取 accessToken
	accessToken, err := c.GetAccessToken()
	if err != nil {
		return rsp, err
	}
	param := map[string]string{
		"access_token": accessToken,
	}
	url := fmt.Sprintf("%s?%s", WorkrecordGetbyuserid, dingtalkhttplib.URLEncode(param))
	log.Println(url)
	req := dingtalkhttplib.Post(url)
	// 添加请求body数据
	jsonData, err := json.Marshal(info)
	if err != nil {
		return rsp, err
	}
	// str2 := string(jsonData[:])
	// fmt.Println(str2)
	req.Body(jsonData)

	b, err := req.AsBytes()
	if err != nil {
		return rsp, err
	}
	err = json.Unmarshal(b, rsp)
	if err != nil {
		return rsp, err
	}
	if rsp.Errcode != 0 {
		return rsp, errors.New(rsp.Errmsg)
	}
	return rsp, nil
}
